Introduction to Python Sequence Data Structures
Course: Python Programming Training
Topic: Introduction to Python Sequence Data Structures
Course Link: Python Training Course – JustAcademy
Demo Registration: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to Sequence Data Structures
Python provides several built-in data structures for storing, organizing, and processing data. A sequence is an ordered collection of elements in which items can generally be accessed using their positions, called indexes. Sequences support operations such as indexing, slicing, iteration, and length checking.
Sequence data structures are useful when working with student records, product lists, text, numerical values, coordinates, dates, and many other types of information.
For example, a program can store several subject names in a list, represent fixed coordinates in a tuple, process individual characters in a string, or generate numbers using a range object.
subjects = ["Python", "SQL", "Power BI"]
coordinates = (10, 20)
message = "Hello"
numbers = range(1, 6)
print(subjects)
print(coordinates)
print(message)
print(list(numbers))
Output:
['Python', 'SQL', 'Power BI']
(10, 20)
Hello
[1, 2, 3, 4, 5]
Understanding sequence data structures helps you select an appropriate way to store and manipulate information in Python programs.
2. Learning Objectives
After completing this topic, you should be able to:
- Explain the meaning and purpose of sequence data structures.
- Understand strings, lists, tuples, and range objects.
- Differentiate between mutable and immutable data types.
- Create and access sequence elements using indexes.
- Use positive and negative indexing.
- Extract portions of sequences using slicing.
- Perform concatenation, repetition, membership testing, and iteration.
- Apply built-in functions such as
len(), min(), max(), and sum() where appropriate.
- Understand the differences between sequences, sets, and dictionaries.
- Choose suitable data structures for practical programming problems.
3. What Is a Sequence in Python?
A sequence is an ordered collection of elements. Each element occupies a position, and Python generally uses zero-based indexing to access that position.
For example, consider the following list:
colors = ["red", "green", "blue"]
Its elements have the following indexes:
| Element |
Positive Index |
Negative Index |
"red" |
0 |
-3 |
"green" |
1 |
-2 |
"blue" |
2 |
-1 |
Python has several built-in sequence types. The most commonly used general-purpose sequences are strings, lists, tuples, and range objects. Other sequence types include bytes and bytearray.
4. Main Types of Python Sequences
| Sequence Type |
Syntax |
Mutable? |
Typical Purpose |
String (str) |
"Python" |
No |
Storing and processing text. |
List (list) |
[10, 20, 30] |
Yes |
Storing collections that may change. |
Tuple (tuple) |
(10, 20, 30) |
No |
Storing ordered groups of values that should not be reassigned through the tuple. |
Range (range) |
range(1, 6) |
No |
Representing regular integer sequences, often for loops. |
Bytes (bytes) |
b"ABC" |
No |
Representing binary data as byte values. |
Bytearray (bytearray) |
bytearray(b"ABC") |
Yes |
Working with modifiable binary data. |
In this topic, we focus mainly on strings, lists, tuples, and ranges because they are common in beginner-level Python programming.
5. Understanding Mutability and Immutability
Mutability describes whether an object can be changed after it has been created.
Mutable Data Structures
A mutable object can be modified without creating a new object for every change. Lists and bytearrays are examples of mutable sequences.
numbers = [10, 20, 30]
numbers[1] = 99
print(numbers)
Output:
[10, 99, 30]
The second element changes from 20 to 99.
Immutable Data Structures
An immutable object cannot have its individual elements reassigned after creation. Strings, tuples, ranges, and bytes are immutable.
message = "Python"
# This would raise TypeError:
# message[0] = "J"
message = "J" + message[1:]
print(message)
Output:
Jython
The original string is not modified. Instead, the expression creates a new string and assigns it to the variable.
6. Introduction to Strings
A string is an immutable sequence of Unicode characters. Strings are used to represent names, messages, addresses, descriptions, passwords, and other text.
6.1 Creating Strings
name = "Aarav"
city = 'Mumbai'
message = """Welcome to Python programming."""
print(name)
print(city)
print(message)
Output:
Aarav
Mumbai
Welcome to Python programming.
Single quotes and double quotes can both define strings. Triple quotes are commonly used for multiline strings and documentation strings.
6.2 Accessing String Characters
language = "Python"
print(language[0])
print(language[2])
print(language[-1])
Output:
P
t
n
6.3 Common String Operations
first = "Hello"
second = "Python"
print(first + " " + second)
print(first * 3)
print(len(second))
print("Py" in second)
Output:
Hello Python
HelloHelloHello
6
True
+ joins strings together.
* repeats a string a specified number of times.
len() returns the number of characters in the string.
in checks whether a substring or character is present.
6.4 Useful String Methods
text = " Learn Python "
print(text.strip())
print(text.lower())
print(text.upper())
print(text.replace("Python", "SQL"))
Output:
Learn Python
learn python
LEARN PYTHON
Learn SQL
String methods generally return new strings because strings are immutable.
7. Introduction to Lists
A list is a mutable, ordered sequence that can contain elements of different data types. Lists are especially useful when a program needs to add, remove, replace, or rearrange values.
7.1 Creating Lists
numbers = [10, 20, 30, 40]
names = ["Aarav", "Diya", "Kabir"]
mixed = [100, "Python", 3.14, True]
empty_list = []
print(numbers)
print(names)
print(mixed)
print(empty_list)
Output:
[10, 20, 30, 40]
['Aarav', 'Diya', 'Kabir']
[100, 'Python', 3.14, True]
[]
7.2 Accessing List Elements
fruits = ["apple", "banana", "mango"]
print(fruits[0])
print(fruits[1])
print(fruits[-1])
Output:
apple
banana
mango
7.3 Modifying List Elements
prices = [100, 200, 300]
prices[1] = 250
print(prices)
Output:
[100, 250, 300]
7.4 Adding Elements to a List
languages = ["Python", "Java"]
languages.append("JavaScript")
languages.insert(1, "SQL")
languages.extend(["HTML", "CSS"])
print(languages)
Output:
['Python', 'SQL', 'Java', 'JavaScript', 'HTML', 'CSS']
append() adds one item at the end.
insert() adds one item at a specified index.
extend() adds items from another iterable.
7.5 Removing Elements from a List
numbers = [10, 20, 30, 40, 20]
numbers.remove(20)
print(numbers)
last_item = numbers.pop()
print(last_item)
print(numbers)
Output:
[10, 30, 40, 20]
20
[10, 30, 40]
remove() removes the first matching value, while pop() removes and returns an item by index or removes the last item by default.
7.6 Sorting and Reversing Lists
scores = [85, 65, 92, 78]
scores.sort()
print(scores)
scores.reverse()
print(scores)
Output:
[65, 78, 85, 92]
[92, 85, 78, 65]
The sort() method sorts a list in place. The reverse() method reverses the existing order in place; it does not sort the values.
8. Introduction to Tuples
A tuple is an ordered, immutable sequence. Tuples are useful for grouping related values when the positions and membership of the group should not be changed through tuple assignment.
8.1 Creating Tuples
coordinates = (10, 20)
person = ("Aarav", 25, "Mumbai")
empty_tuple = ()
single_item_tuple = (5,)
print(coordinates)
print(person)
print(single_item_tuple)
Output:
(10, 20)
('Aarav', 25, 'Mumbai')
(5,)
A comma is required to create a single-item tuple. Parentheses alone do not make an ordinary expression into a tuple.
value = (5)
tuple_value = (5,)
print(type(value))
print(type(tuple_value))
Output:
<class 'int'>
<class 'tuple'>
8.2 Accessing Tuple Elements
colors = ("red", "green", "blue")
print(colors[0])
print(colors[-1])
Output:
red
blue
8.3 Tuple Packing and Unpacking
Tuple packing groups values into a tuple. Unpacking assigns the tuple's elements to separate variables.
student = ("Diya", 21, "Python")
name, age, course = student
print(name)
print(age)
print(course)
Output:
Diya
21
Python
The number of variables on the left must match the number of unpacked elements unless extended unpacking is used.
8.4 Why Use Tuples?
- To represent fixed groups of related values.
- To return multiple values from a function.
- To represent coordinates, dimensions, or fixed records.
- To communicate that a collection should not be structurally changed.
Note that a tuple can contain a mutable object such as a list. The tuple itself remains immutable, but the contained list may still be modified.
9. Introduction to Range Objects
A range object represents an immutable sequence of integers. It is commonly used with for loops when a program needs to repeat an operation a specific number of times.
9.1 Creating a Range
numbers = range(1, 6)
print(list(numbers))
Output:
[1, 2, 3, 4, 5]
9.2 The Three Forms of range()
range(stop)
range(start, stop)
range(start, stop, step)
| Expression |
Generated Values |
range(5) |
0, 1, 2, 3, 4 |
range(2, 6) |
2, 3, 4, 5 |
range(2, 11, 2) |
2, 4, 6, 8, 10 |
range(5, 0, -1) |
5, 4, 3, 2, 1 |
The stop value is excluded. The step controls the difference between consecutive values and cannot be zero.
9.3 Iterating Through a Range
for number in range(1, 6):
print(number)
Output:
1
2
3
4
5
Range objects are memory-efficient because they represent the integer progression instead of storing every generated number in a list.
10. Indexing in Python Sequences
Indexing accesses an individual element using its position. Python sequences generally use zero-based indexing, which means the first element is at index 0.
10.1 Positive Indexing
languages = ["Python", "Java", "SQL", "HTML"]
print(languages[0])
print(languages[2])
Output:
Python
SQL
10.2 Negative Indexing
Negative indexes count from the end of the sequence. The index -1 identifies the last element, -2 identifies the second-to-last element, and so on.
languages = ["Python", "Java", "SQL", "HTML"]
print(languages[-1])
print(languages[-2])
Output:
HTML
SQL
10.3 IndexError
Accessing an index outside the valid range raises IndexError.
numbers = [10, 20, 30]
# This raises IndexError:
# print(numbers[3])
The valid positive indexes for this list are 0, 1, and 2. Use len(numbers) to determine the number of elements.
11. Slicing Sequences
Slicing extracts a portion of a sequence without requiring you to access every element individually.
11.1 Slicing Syntax
sequence[start:stop:step]
- start: The index where the slice begins, included by the slice.
- stop: The index where the slice ends, excluded by the slice.
- step: The interval between selected elements.
11.2 List Slicing Examples
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4])
print(numbers[:3])
print(numbers[3:])
print(numbers[::2])
print(numbers[::-1])
Output:
[20, 30, 40]
[10, 20, 30]
[40, 50, 60]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]
11.3 String Slicing
message = "Programming"
print(message[:7])
print(message[7:])
print(message[::2])
Output:
Program
ming
Pormig
Slicing is useful for extracting text, selecting ranges of values, creating reversed copies, and processing data in chunks.
12. Common Operations on Sequences
Several operations work with multiple sequence types, although some types have additional restrictions.
12.1 Length
The len() function returns the number of elements in a sequence.
numbers = [10, 20, 30, 40]
message = "Python"
print(len(numbers))
print(len(message))
Output:
4
6
12.2 Concatenation
The + operator joins compatible sequences of the same type.
first = [1, 2]
second = [3, 4]
print(first + second)
print("Data" + "Science")
Output:
[1, 2, 3, 4]
DataScience
Concatenation generally requires compatible types. For example, a list cannot be concatenated directly with a tuple using +.
12.3 Repetition
The * operator repeats a sequence a specified number of times.
print([1, 2] * 3)
print("Hi " * 3)
Output:
[1, 2, 1, 2, 1, 2]
Hi Hi Hi
12.4 Membership Testing
The in and not in operators check whether a value or substring exists in a sequence.
fruits = ["apple", "banana", "mango"]
print("banana" in fruits)
print("orange" not in fruits)
Output:
True
True
12.5 Minimum, Maximum, and Sum
For suitable sequences of comparable values, min() and max() return the smallest and largest elements. The sum() function adds numeric elements.
scores = [75, 92, 68, 88]
print(min(scores))
print(max(scores))
print(sum(scores))
Output:
68
92
323
sum() is intended for numeric values. Mixed types or values that cannot be compared may produce errors when using these functions.
13. Iterating Through Sequences
Iteration means processing sequence elements one at a time. Python's for loop is the standard way to iterate over strings, lists, tuples, and ranges.
13.1 Iterating Through a List
subjects = ["Python", "SQL", "Excel"]
for subject in subjects:
print(subject)
Output:
Python
SQL
Excel
13.2 Iterating Through a String
word = "CODE"
for character in word:
print(character)
Output:
C
O
D
E
13.3 Iterating Through a Tuple
coordinates = (10, 20, 30)
for coordinate in coordinates:
print(coordinate)
Output:
10
20
30
13.4 Iterating with Indexes Using enumerate()
The enumerate() function provides an index and value during each iteration.
names = ["Aarav", "Diya", "Kabir"]
for index, name in enumerate(names, start=1):
print(index, name)
Output:
1 Aarav
2 Diya
3 Kabir
This is usually clearer than manually using range(len(names)) when you need both indexes and values.
14. List Methods and Built-In Functions
Lists provide methods for managing their contents. These methods are particularly useful when processing dynamic collections.
| Method or Function |
Purpose |
Example |
append(x) |
Adds one element at the end. |
items.append(10) |
extend(iterable) |
Adds elements from another iterable. |
items.extend([20, 30]) |
insert(i, x) |
Inserts an element at an index. |
items.insert(0, 5) |
remove(x) |
Removes the first matching value. |
items.remove(10) |
pop(i) |
Removes and returns an element. |
items.pop() |
index(x) |
Returns the index of the first matching value. |
items.index(20) |
count(x) |
Counts occurrences of a value. |
items.count(10) |
sort() |
Sorts the list in place. |
items.sort() |
reverse() |
Reverses the list in place. |
items.reverse() |
clear() |
Removes all elements. |
items.clear() |
Example: Analyzing a List of Scores
scores = [75, 88, 75, 92, 64, 88]
print("Number of scores:", len(scores))
print("Score of 75 occurs:", scores.count(75), "times")
print("Highest score:", max(scores))
print("Lowest score:", min(scores))
scores.append(95)
print("Updated scores:", scores)
Output:
Number of scores: 6
Score of 75 occurs: 2 times
Highest score: 92
Lowest score: 64
Updated scores: [75, 88, 75, 92, 64, 88, 95]
15. Difference Between List and Tuple
Lists and tuples are both ordered sequences. Their primary difference is mutability.
| Feature |
List |
Tuple |
| Syntax |
Square brackets: [] |
Usually parentheses: () |
| Mutability |
Mutable |
Immutable |
| Element assignment |
Allowed |
Not allowed |
| Adding or removing elements |
Supported |
Not supported directly |
| Common use |
Collections that change |
Fixed groups of values |
| Methods |
Many methods for modifying elements |
Fewer methods, including count() and index() |
Example Comparison
my_list = [10, 20, 30]
my_tuple = (10, 20, 30)
my_list[0] = 99
print(my_list)
print(my_tuple)
Output:
[99, 20, 30]
(10, 20, 30)
Choose a list when the collection needs to change. Choose a tuple when an ordered group of values should remain fixed through tuple operations.
16. Difference Between Sequences, Sets, and Dictionaries
Python also provides sets and dictionaries. They are important data structures, but they are not sequence types.
| Feature |
Sequence |
Set |
Dictionary |
| Examples |
List, tuple, string, range |
{10, 20, 30} |
{"name": "Aarav"} |
| Organization |
Ordered positions |
Unique elements, without positional indexing |
Key-value pairs |
| Access |
Usually by integer index |
Membership testing or iteration |
By key or through iteration |
| Duplicates |
Generally allowed |
Not retained as separate elements |
Keys must be unique; values may repeat |
| Typical use |
Ordered collections |
Unique items and set operations |
Mapping keys to values |
Set Example
numbers = {10, 20, 20, 30}
print(numbers)
print(20 in numbers)
The set contains only one occurrence of each value. Its display order should not be relied upon.
Dictionary Example
student = {
"name": "Aarav",
"age": 21,
"course": "Python"
}
print(student["name"])
print(student["course"])
Output:
Aarav
Python
Dictionaries preserve insertion order in modern Python, but they are mappings accessed by keys rather than integer-indexed sequences.
17. Nested Sequences
A sequence can contain other sequences. This allows Python to represent tables, matrices, grids, and structured records.
17.1 List of Lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0])
print(matrix[1][2])
print(matrix[2][0])
Output:
[1, 2, 3]
6
7
The first index selects an inner list, while the second index selects an element within that list.
17.2 Iterating Through a Matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for value in row:
print(value, end=" ")
print()
Output:
1 2 3
4 5 6
7 8 9
Nested sequences are useful for representing tabular data, game boards, seating plans, and numerical matrices.
18. List Comprehensions
A list comprehension creates a new list by applying an expression to each item in an iterable. It can also include a condition to filter the results.
18.1 Creating a List of Squares
squares = [number ** 2 for number in range(1, 6)]
print(squares)
Output:
[1, 4, 9, 16, 25]
18.2 Filtering Values
numbers = [10, 15, 20, 25, 30]
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)
Output:
[10, 20, 30]
18.3 Converting Strings to Uppercase
names = ["aarav", "diya", "kabir"]
uppercase_names = [name.upper() for name in names]
print(uppercase_names)
Output:
['AARAV', 'DIYA', 'KABIR']
List comprehensions are concise and useful for simple transformations. For complicated logic, a regular loop may be easier to read and maintain.
19. Copying Sequences and Avoiding Common Reference Errors
Assigning a list to another variable does not automatically create an independent copy. Both variables may refer to the same list object.
Example: Shared Reference
first = [10, 20, 30]
second = first
second[0] = 99
print(first)
print(second)
Output:
[99, 20, 30]
[99, 20, 30]
Because both variables refer to the same list, modifying the list through one variable is visible through the other.
Creating a Shallow Copy
first = [10, 20, 30]
second = first.copy()
second[0] = 99
print(first)
print(second)
Output:
[10, 20, 30]
[99, 20, 30]
The copy() method creates a shallow copy of a list. For nested lists or other nested mutable objects, a shallow copy does not independently copy every nested object. Use the copy module's deepcopy() when an independent recursive copy is required.
20. Common Errors When Working with Sequences
| Error |
Cause |
Solution |
IndexError |
Accessing an invalid sequence index. |
Check the sequence length and valid index range. |
TypeError |
Trying to modify an immutable sequence or combining incompatible types. |
Use an appropriate mutable type or create a new object. |
ValueError |
Calling a method such as remove() with a value that is not present. |
Check membership or handle the exception. |
| Unexpected duplicates |
Adding an element that already exists in a list. |
Use a set or check membership if uniqueness is required. |
| Unexpected list changes |
Two variables reference the same list. |
Create a copy when independent data is required. |
| Incorrect slice results |
Misunderstanding the excluded stop index. |
Remember that slicing includes the start and excludes the stop. |
| Unexpected set order |
Relying on set iteration order. |
Use sorted() when ordered output is required and the elements are comparable. |
| Confusing tuple syntax |
Creating a single value inside parentheses without a trailing comma. |
Use (value,) for a one-element tuple. |
21. Best Practices for Working with Sequences
- Choose a list when you need to modify a collection frequently.
- Choose a tuple for an ordered group of values that should not be reassigned through tuple operations.
- Use strings for text and avoid attempting to modify characters by index.
- Use range objects for integer progressions instead of creating large lists unnecessarily.
- Prefer direct iteration when indexes are not needed.
- Use
enumerate() when you need both the position and value of each item.
- Use descriptive variable names such as
student_names, scores, and coordinates.
- Use slicing to extract portions of sequences clearly.
- Make copies when you need to modify a list independently from its original.
- Use a set when uniqueness and membership testing are more important than positional order.
- Use a dictionary when values should be retrieved through meaningful keys.
- Validate indexes and handle missing values where necessary.
22. Practical Project: Student Record Manager
This beginner project demonstrates how lists, tuples, indexing, iteration, and built-in functions can be combined to manage a small set of student records.
Project Requirements
- Store student names and scores.
- Display each student's information.
- Calculate the average score.
- Identify the highest score.
- Allow a new student record to be added.
Program
students = [
("Aarav", 85),
("Diya", 92),
("Kabir", 78)
]
print("STUDENT RECORDS")
print("----------------")
for name, score in students:
print(f"Name: {name}, Score: {score}")
scores = [score for name, score in students]
average = sum(scores) / len(scores)
highest_score = max(scores)
print("----------------")
print("Average Score:", round(average, 2))
print("Highest Score:", highest_score)
new_name = input("Enter a new student name: ")
new_score = int(input("Enter the student's score: "))
students.append((new_name, new_score))
print("\nUPDATED RECORDS")
for name, score in students:
print(f"{name}: {score}")
Sample Output
STUDENT RECORDS
----------------
Name: Aarav, Score: 85
Name: Diya, Score: 92
Name: Kabir, Score: 78
----------------
Average Score: 85.0
Highest Score: 92
Enter a new student name: Meera
Enter the student's score: 88
UPDATED RECORDS
Aarav: 85
Diya: 92
Kabir: 78
Meera: 88
Concepts Used
- A list stores the collection of student records.
- Each tuple represents a student's name and score.
- A
for loop iterates over the records.
- A list comprehension extracts the scores.
sum(), len(), and max() calculate useful statistics.
append() adds a new record to the list.
For a production-ready application, add validation for empty names, invalid scores, and non-numeric input.
23. Practice Exercises
Beginner Exercises
- Create a list of five favorite programming languages and display each language.
- Create a tuple containing three city names and access its first and last elements.
- Store a sentence in a string and count its characters using
len().
- Use
range() to generate integers from 1 through 20.
- Extract the first three elements of a list using slicing.
- Check whether a particular value exists in a list using
in.
Intermediate Exercises
- Find the largest and smallest numbers in a numeric list.
- Remove duplicate values from a list while preserving the original order.
- Use a list comprehension to create a list of squares of even numbers.
- Combine two lists using concatenation.
- Count how many times a particular value appears in a list.
- Create a dictionary of student details and access values using keys.
- Store matrix data in a nested list and print each row.
Advanced Exercises
- Build a program that accepts student names and scores and calculates summary statistics.
- Write a function that returns a new list containing only unique elements in their original order.
- Compare shallow copying and deep copying using a nested list.
- Create a sequence-processing program that separates even and odd numbers.
- Build a simple inventory manager using a list of dictionaries.
24. Interview Questions and Answers
Q1. What is a sequence in Python?
Answer: A sequence is an ordered collection of elements that supports operations such as indexing, slicing, and iteration.
Q2. Name four common Python sequence types.
Answer: Strings, lists, tuples, and range objects.
Q3. What is the difference between mutable and immutable sequences?
Answer: Mutable sequences can be modified after creation, while immutable sequences do not allow their elements to be reassigned. Lists are mutable; strings and tuples are immutable.
Q4. Why does Python use zero-based indexing?
Answer: Zero-based indexing identifies the first element with index 0 and allows index calculations to work naturally with offsets and sequence lengths.
Q5. What is negative indexing?
Answer: Negative indexing accesses elements relative to the end of a sequence. Index -1 identifies the last element.
Q6. What is slicing?
Answer: Slicing extracts a portion of a sequence using the syntax sequence[start:stop:step].
Q7. What is the difference between a list and a tuple?
Answer: Both are ordered sequences, but lists are mutable and tuples are immutable.
Q8. How do you create a single-element tuple?
Answer: Add a trailing comma, as in (10,).
Q9. What is the purpose of range()?
Answer: It represents an immutable sequence of integers and is commonly used for iteration in loops.
Q10. What is the difference between append() and extend()?
Answer: append() adds one object as an element. extend() adds the elements supplied by an iterable.
Q11. How can you reverse a sequence?
Answer: For many sequences, use slicing such as sequence[::-1]. For a reversible iterable, use reversed(). Lists also provide an in-place reverse() method.
Q12. Can a tuple contain a list?
Answer: Yes. A tuple can contain a list, but the tuple's reference to that list cannot be reassigned through tuple indexing. The list itself can still be modified.
Q13. What is a nested list?
Answer: A nested list is a list that contains other lists. It can represent tables, matrices, and other structured data.
Q14. What is the purpose of enumerate()?
Answer: It returns an iterator of index-value pairs, making it useful when both the position and value are needed during iteration.
Q15. Are sets sequence types?
Answer: No. Sets are collections of unique elements without positional indexing. They are useful for membership testing and set operations.
25. Quick Revision Checklist
- A sequence is an ordered collection of elements.
- Strings, lists, tuples, and ranges are common sequence types.
- Lists are mutable; strings, tuples, and ranges are immutable.
- Python sequence indexing generally starts at zero.
- Negative indexing accesses elements from the end.
- Slicing uses
sequence[start:stop:step].
- The stop boundary in a slice is excluded.
len() returns the number of elements.
append() adds one element to a list.
extend() adds elements from an iterable.
enumerate() supplies index-value pairs.
- Tuples can represent fixed groups of related values.
- Range objects represent integer progressions efficiently.
- Sets store unique elements and do not support positional indexing.
- Dictionaries map keys to values.
- Use copying techniques when you need an independent list.
26. Conclusion
Python sequence data structures provide practical ways to store, organize, access, and process data. Strings are suitable for text, lists are useful for collections that change, tuples represent ordered groups of values that should not be reassigned through tuple operations, and range objects represent regular sequences of integers.
By learning indexing, slicing, iteration, common sequence operations, and mutability, you can write clearer and more reliable Python programs. Understanding the difference between sequences, sets, and dictionaries also helps you choose the right data structure for each programming task.
Practice the examples and exercises in these notes, then apply the concepts to projects such as student record managers, inventory systems, text analyzers, and numerical tools.
Continue Learning with JustAcademy
Explore additional Python programming topics and strengthen your practical coding skills.